<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单/交易号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="退款状态" prop="refundStatus" style="width: 300px;">
        <el-select v-model="queryParams.refundStatus" placeholder="请选择退款状态">
          <el-option label="未退款" value="1" />
          <el-option label="已退款" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="退款时间" prop="refundTime">
        <el-date-picker clearable v-model="queryParams.refundTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择退款时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="refundList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="售后单号" align="center" prop="afterSaleNo" />
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="第三方付款流水号" align="center" prop="thirdPaymentNo" min-width="200">
        <template #default="scope">
          <div style="display: flex; align-items: center; gap: 8px;">
            <el-tooltip v-if="scope.row.thirdPaymentNo && scope.row.thirdPaymentNo.length > 15 && scope.row.thirdPaymentNo !== '未找到' && scope.row.thirdPaymentNo !== '查询失败'" 
                        :content="scope.row.thirdPaymentNo" placement="top">
              <span>{{ scope.row.thirdPaymentNo ? scope.row.thirdPaymentNo.substring(0, 15) + '...' : '-' }}</span>
            </el-tooltip>
            <span v-else-if="scope.row.thirdPaymentNo === '查询失败'" style="color: #f56c6c;">{{ scope.row.thirdPaymentNo }}</span>
            <span v-else-if="scope.row.thirdPaymentNo === '未找到'" style="color: #909399;">{{ scope.row.thirdPaymentNo }}</span>
            <span v-else>{{ scope.row.thirdPaymentNo || '-' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="第三方退款流水号" align="center" prop="thirdRefundNo" min-width="200">
        <template #default="scope">
          <div style="display: flex; align-items: center; gap: 8px;">
            <el-tooltip v-if="scope.row.thirdRefundNo && scope.row.thirdRefundNo.length > 15" 
                        :content="scope.row.thirdRefundNo" placement="top">
              <span>{{ scope.row.thirdRefundNo.substring(0, 15) + '...' }}</span>
            </el-tooltip>
            <span v-else-if="scope.row.thirdRefundNo">{{ scope.row.thirdRefundNo }}</span>
            <span v-else style="color: #909399;">{{ generateThirdRefundNoDisplay(scope.row) }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="退款金额" align="center" prop="refundAmount">
        <!-- 需要有小数点后两位 -->
        <template #default="scope">
          <span style="color: red;">￥{{ scope.row.refundAmount.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户提交退款申请的时间" align="center" prop="applyTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款状态" align="center" prop="refundStatus">
        <template #default="scope">
          <el-tag :type="scope.row.refundStatus === 1 ? 'danger' : 'success'">
            {{ scope.row.refundStatus === 1 ? '未退款' : '已退款' }}
          </el-tag>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
  </div>
</template>

<script setup name="Refund">
import { listRefund, updateRefund } from "@/api/orders/refund"
import { listPayment } from "@/api/orders/payment"

const { proxy } = getCurrentInstance()

const refundList = ref([])
const open = ref(false)
const loading = ref(true)
const paymentLoading = ref(false)
const batchLoading = ref(false)
const manualLoading = ref(false)
const showSearch = ref(true)
const total = ref(0)
const selectedRows = ref([])
const manualOrderNo = ref('')

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    refundNo: null,
    afterSaleNo: null,
    orderNo: null,
    thirdPaymentNo: null,
    thirdRefundNo: null,
    refundAmount: null,
    applyTime: null,
    refundStatus: null,
    paymentMethod: null,
    memberId: null,
    merchantId: null,
    refundTime: null,
    refundCompleteTime: null,
    failReason: null
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 生成退款流水号 */
function generateRefundNo(refund) {
  if (!refund.afterSaleNo) {
    proxy.$modal.msgError('售后单号不能为空，无法生成退款流水号')
    return
  }

  if (refund.refundNo) {
    proxy.$modal.msgWarning('该记录已有退款流水号')
    return
  }

  refund.generatingRefundNo = true

  // 根据售后单号生成退款流水号
  // 格式：RF + 售后单号 + 时间戳后6位
  const timestamp = Date.now().toString().slice(-6)
  const newRefundNo = `RF${refund.afterSaleNo}${timestamp}`

  // 更新退款记录
  const updateData = {
    ...refund,
    refundNo: newRefundNo
  }

  updateRefund(updateData).then(response => {
    if (response.code === 200) {
      refund.refundNo = newRefundNo
      proxy.$modal.msgSuccess('退款流水号生成成功')
      console.log(`售后单号 ${refund.afterSaleNo} 生成退款流水号: ${newRefundNo}`)
    } else {
      proxy.$modal.msgError('退款流水号生成失败')
    }
  }).catch(error => {
    console.error('生成退款流水号失败:', error)
    proxy.$modal.msgError('退款流水号生成失败')
  }).finally(() => {
    refund.generatingRefundNo = false
  })
}

/** 批量生成退款流水号 */
async function batchGenerateRefundNo() {
  if (selectedRows.value.length === 0) {
    proxy.$modal.msgError('请选择要生成流水号的记录')
    return
  }

  // 过滤出没有退款流水号的记录
  const needGenerateRefunds = selectedRows.value.filter(refund => !refund.refundNo)
  
  if (needGenerateRefunds.length === 0) {
    proxy.$modal.msgWarning('选中的记录都已生成退款流水号')
    return
  }

  try {
    batchLoading.value = true
    let successCount = 0
    let failCount = 0

    for (const refund of needGenerateRefunds) {
      try {
        if (!refund.afterSaleNo) {
          console.warn(`售后单号为空，跳过: ${refund.orderNo}`)
          failCount++
          continue
        }

        // 生成退款流水号
        const timestamp = Date.now().toString().slice(-6)
        const newRefundNo = `RF${refund.afterSaleNo}${timestamp}`

        // 更新退款记录
        const updateData = {
          ...refund,
          refundNo: newRefundNo
        }

        const response = await updateRefund(updateData)
        if (response.code === 200) {
          refund.refundNo = newRefundNo
          successCount++
          console.log(`售后单号 ${refund.afterSaleNo} 生成退款流水号: ${newRefundNo}`)
        } else {
          failCount++
          console.error(`售后单号 ${refund.afterSaleNo} 生成退款流水号失败`)
        }
      } catch (error) {
        console.error(`生成退款流水号失败:`, error)
        failCount++
      }
    }

    // 强制更新视图
    refundList.value = [...refundList.value]

    if (successCount > 0) {
      proxy.$modal.msgSuccess(`批量生成完成！成功: ${successCount} 条，失败: ${failCount} 条`)
    } else {
      proxy.$modal.msgError('批量生成失败，请检查售后单号是否完整')
    }

  } catch (error) {
    console.error('批量生成退款流水号失败:', error)
    proxy.$modal.msgError('批量生成退款流水号失败')
  } finally {
    batchLoading.value = false
  }
}

/** 查询退款记录列表 */
function getList() {
  loading.value = true
  listRefund(queryParams.value).then(response => {
    refundList.value = response.rows
    total.value = response.total
    loading.value = false
    
    // 为每个退款记录添加loading状态
    refundList.value.forEach(refund => {
      refund.paymentLoading = false
      refund.generatingRefundNo = false
    })
    
    // 为每个退款记录查询对应的支付记录，获取第三方付款流水号
    if (refundList.value && refundList.value.length > 0) {
      getPaymentNumbersForRefunds()
    }
  }).catch(error => {
    console.error('查询退款记录失败:', error)
    loading.value = false
  })
}

/** 为退款记录获取支付流水号 */
function getPaymentNumbersForRefunds() {
  paymentLoading.value = true
  const paymentPromises = refundList.value.map(refund => {
    if (refund.orderNo) {
      return listPayment({ orderNo: refund.orderNo }).then(paymentResponse => {
        if (paymentResponse.rows && paymentResponse.rows.length > 0) {
          // 查找匹配的支付记录
          const paymentRecord = paymentResponse.rows.find(payment => 
            payment.orderId === refund.orderNo || payment.orderId === refund.orderNo
          )
          
          if (paymentRecord && paymentRecord.thirdPartyTransactionId) {
            refund.thirdPaymentNo = paymentRecord.thirdPartyTransactionId
            console.log(`订单 ${refund.orderNo} 获取到流水号: ${paymentRecord.thirdPartyTransactionId}`)
          } else {
            refund.thirdPaymentNo = '未找到'
            console.log(`订单 ${refund.orderNo} 未找到支付记录或流水号`)
          }
        } else {
          refund.thirdPaymentNo = '未找到'
          console.log(`订单 ${refund.orderNo} 未找到支付记录`)
        }
        return refund
      }).catch(error => {
        console.error(`查询订单 ${refund.orderNo} 支付记录失败:`, error)
        refund.thirdPaymentNo = '查询失败'
        return refund
      })
    }
    return Promise.resolve(refund)
  })
  
  // 等待所有支付记录查询完成
  Promise.all(paymentPromises).then(() => {
    // 强制更新视图
    refundList.value = [...refundList.value]
    paymentLoading.value = false
  }).catch(() => {
    paymentLoading.value = false
  })
}

/** 单个订单获取流水号 */
async function getPaymentNoForOrder(refund) {
  if (!refund.orderNo) {
    proxy.$modal.msgError('订单号不能为空')
    return
  }

  refund.paymentLoading = true

  try {
    const paymentResponse = await listPayment({ orderNo: refund.orderNo })

    if (paymentResponse.rows && paymentResponse.rows.length > 0) {
      // 查找匹配的支付记录
      const paymentRecord = paymentResponse.rows.find(payment =>
        payment.orderId === refund.orderNo || payment.orderId === refund.orderNo
      )

      if (paymentRecord && paymentRecord.thirdPartyTransactionId) {
        refund.thirdPaymentNo = paymentRecord.thirdPartyTransactionId
        proxy.$modal.msgSuccess(`订单 ${refund.orderNo} 流水号获取成功`)
        console.log(`订单 ${refund.orderNo} 获取到流水号: ${paymentRecord.thirdPartyTransactionId}`)
      } else {
        refund.thirdPaymentNo = '未找到'
        proxy.$modal.msgWarning(`订单 ${refund.orderNo} 未找到支付流水号`)
      }
    } else {
      refund.thirdPaymentNo = '未找到'
      proxy.$modal.msgWarning(`订单 ${refund.orderNo} 未找到支付记录`)
    }

    // 强制更新视图
    refundList.value = [...refundList.value]

  } catch (error) {
    console.error(`查询订单 ${refund.orderNo} 支付记录失败:`, error)
    refund.thirdPaymentNo = '查询失败'
    proxy.$modal.msgError(`查询订单 ${refund.orderNo} 支付记录失败`)
  } finally {
    refund.paymentLoading = false
  }
}

/** 生成第三方退款流水号显示 */
function generateThirdRefundNoDisplay(refund) {
  if (!refund.afterSaleNo) {
    return '售后单号为空'
  }
  
  if (refund.thirdRefundNo) {
    return refund.thirdRefundNo
  }
  
  // 根据售后单号生成第三方退款流水号
  // 格式：RF + 售后单号 + 时间戳后6位
  const timestamp = Date.now().toString().slice(-6)
  const newThirdRefundNo = `RF${refund.afterSaleNo}${timestamp}`
  
  // 自动更新退款记录
  const updateData = {
    ...refund,
    thirdRefundNo: newThirdRefundNo
  }
  
  updateRefund(updateData).then(response => {
    if (response.code === 200) {
      refund.thirdRefundNo = newThirdRefundNo
      console.log(`售后单号 ${refund.afterSaleNo} 自动生成第三方退款流水号: ${newThirdRefundNo}`)
    } else {
      console.error(`售后单号 ${refund.afterSaleNo} 自动生成第三方退款流水号失败`)
    }
  }).catch(error => {
    console.error('自动生成第三方退款流水号失败:', error)
  })
  
  return newThirdRefundNo
}

/** 选择行变化 */
function handleSelectionChange(selection) {
  selectedRows.value = selection
}


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

getList()
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}

.el-table .el-button--small {
  padding: 5px 10px;
  font-size: 12px;
}

.el-tag {
  font-family: 'Courier New', monospace;
  font-weight: bold;
}
</style>
